const { app, BrowserWindow, globalShortcut, Menu } = require('electron')
const localShortcut = require('electron-localshortcut')

const path = require('path')

app.whenReady().then(()=>{
  createWindow()
  createApplicationMenu()
  registerGlobalShortcut('Cmd+Alt+K')
})

// 创建窗口
let win1= null
let win2 = null
function createWindow() {
  const width = 600
  const height = 800
  win1 = new BrowserWindow({
    width: width,
    height: height,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      sandbox: false,
    },
  })
  win1.loadFile(path.join(__dirname,'../renderer/index.html'))
  // 注册应用快捷键
  localShortcut.register(win1,'Ctrl+Shift+K',()=>{
    console.log('win1 shortcut register success')
  })
//   win2 = new BrowserWindow({width,height})
//   win2.loadURL('https://www.baidu.com')
//   localShortcut.register(win2,'Ctrl+Shift+T',()=>{
//     console.log('win1 shortcut register success')
//   })
//   win1.webContents.openDevTools({mode: 'detach'})
  
}

// 应用快捷键
function createApplicationMenu() {
    const tpl = [
        {
            label: '自定义菜单',
            submenu: [
                {
                label: '打开控制台',
                role: 'toggleDevTools',
                },
                {
                label: '绑定快捷键',
                accelerator: 'Ctrl+Shift+L',
                visible: false,
                click: () => {
                    console.log('menu shortcut pressed')
                },
                },
            ],
        },
    ]
    if(process.platform === 'darwin') {
        tpl.unshift({label:''})
    }
    const menu = Menu.buildFromTemplate(tpl)
    Menu.setApplicationMenu(menu)
}

// 注册全局快捷键
function registerGlobalShortcut(shortcut) {
    if(!shortcut) return false
    let flag = false
    try {
        flag = globalShortcut.isRegistered(shortcut)
        if(flag) return true
        flag = globalShortcut.register(shortcut,()=>{
            win2 = new BrowserWindow({width:600,height:800})
            win2.loadURL('https://www.baidu.com')
            localShortcut.register(win2,'Ctrl+Shift+T',()=>{
                console.log('win1 shortcut register success')
            })
            console.log('toggle shortcut')
        })
    }catch(e) {
        console.error(e)
    }
    return flag
}
